#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最简单的实时语音转文字程序
只需要安装: pip install SpeechRecognition PyAudio
"""

import speech_recognition as sr


def main():
    # 创建识别器
    r = sr.Recognizer()

    # 使用麦克风
    with sr.Microphone() as source:
        print("正在调整环境噪声...")
        r.adjust_for_ambient_noise(source, duration=1)
        print("开始说话吧！")

        while True:
            try:
                # 监听音频
                audio = r.listen(source, timeout=3, phrase_time_limit=5)

                # 识别语音
                text = r.recognize_sphinx(audio)
                print(f"你说: {text}")

            except sr.WaitTimeoutError:
                print("等待中...")
            except sr.UnknownValueError:
                print("没听清楚，请再说一遍")
            except sr.RequestError:
                print("网络连接有问题")
            except KeyboardInterrupt:
                print("\n程序退出")
                break


if __name__ == "__main__":
    main()
